//
//  WeatherView.swift
//  JTYP
//
//  Created by Groot on 2017/12/4.
//  Copyright © 2017年 inspur. All rights reserved.
//

import Alamofire

class WeatherView: UIView {
    
    @IBOutlet weak var contantView: UIView!
    @IBOutlet weak var iconView: UIImageView!
    @IBOutlet weak var tempBtn: UIButton!
    @IBOutlet weak var weatherLab: UILabel!
    
    var forecast: HeWeatherDailyForecast?
    
    override func awakeFromNib() {
        request()
        
        self.tempBtn.addTarget(self, action: #selector(request), for: .touchUpInside)
    }
    
    @objc func request()  {
        requestReset()
        
        var params = Parameters()
        params["location"] = "济南"
        params["key"] = API_KEY.KEYHeWeather
        
        NetWorkUtil.shareInstance.getForObject(objectType: heWeatherBaseClass.self, urlString: Server.heWeather, parameters: params, tokenNeeded: false) { [unowned self](obj, error) in
            
            let heweather = obj?.HeWeather6?.first
            
            guard heweather?.status == "ok", heweather?.daily_forecast?.count ?? 0 > 0 else{
                self.requestFailed()
                return
            }
            self.forecast = heweather?.daily_forecast?.first
            
            self.iconView.image = UIImage.init(named: "w\(self.forecast?.cond_code_d ?? "100")")
            self.tempBtn.setTitle("\(self.forecast?.tmp_min ?? "-") - \(self.forecast?.tmp_max ?? "-")℃", for: .normal)
            self.weatherLab.text = self.forecast?.cond_txt_d ?? ""
        }
    }
    
    func requestFailed() {
        self.tempBtn.setTitle("无法获取天气，点击重试", for: .normal)
        self.tempBtn.isEnabled = true
        self.weatherLab.text = ""
        self.iconView.image = nil
    }
    
    func requestReset() {
        self.iconView.image = nil
        self.tempBtn.setTitle("-/-℃", for: .normal)
        self.weatherLab.text = ""
        self.tempBtn.isEnabled = false
    }
}
